package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.dto.ArticleLikeDTO;
import com.example.entity.Article;
import com.example.mapper.ArticleMapper;
import com.example.service.ArticleLikeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 文章点赞服务实现类
 */
@Slf4j
@Service
public class ArticleLikeServiceImpl implements ArticleLikeService {

    @Resource
    private ArticleMapper articleMapper;
    
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean toggleLike(ArticleLikeDTO articleLikeDTO, Integer userId) {
        if (articleLikeDTO == null || articleLikeDTO.getArticleId() == null || userId == null) {
            log.error("点赞文章参数错误: articleId={}, userId={}", 
                    articleLikeDTO != null ? articleLikeDTO.getArticleId() : "null", userId);
            return false;
        }
        
        Integer articleId = articleLikeDTO.getArticleId();
        boolean hasLiked = hasLiked(articleId, userId);
        
        try {
            // 获取文章
            Article article = articleMapper.selectById(articleId);
            if (article == null) {
                log.error("文章不存在: articleId={}", articleId);
                return false;
            }
            
            Integer likeCount = article.getLikeCount();
            if (likeCount == null) {
                likeCount = 0;
            }
            
            if (hasLiked) {
                // 已点赞，取消点赞
                try {
                    String deleteSql = "DELETE FROM tb_article_like WHERE article_id = ? AND user_id = ?";
                    jdbcTemplate.update(deleteSql, articleId, userId);
                    
                    // 更新点赞数
                    article.setLikeCount(Math.max(likeCount - 1, 0));
                    articleMapper.updateById(article);
                    
                    log.info("用户[{}]取消点赞文章[{}]成功，当前点赞数: {}", userId, articleId, article.getLikeCount());
                    return false; // 返回false表示当前未点赞
                } catch (Exception e) {
                    log.error("取消点赞失败: articleId={}, userId={}, error={}", articleId, userId, e.getMessage(), e);
                    throw e;
                }
            } else {
                // 未点赞，添加点赞
                try {
                    String insertSql = "INSERT INTO tb_article_like (article_id, user_id, create_time) VALUES (?, ?, NOW())";
                    jdbcTemplate.update(insertSql, articleId, userId);
                    
                    // 更新点赞数
                    article.setLikeCount(likeCount + 1);
                    articleMapper.updateById(article);
                    
                    log.info("用户[{}]点赞文章[{}]成功，当前点赞数: {}", userId, articleId, article.getLikeCount());
                    return true; // 返回true表示当前已点赞
                } catch (Exception e) {
                    log.error("点赞失败: articleId={}, userId={}, error={}", articleId, userId, e.getMessage(), e);
                    throw e;
                }
            }
        } catch (Exception e) {
            log.error("处理文章点赞操作异常: articleId={}, userId={}, error={}", articleId, userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public boolean hasLiked(Integer articleId, Integer userId) {
        if (articleId == null || userId == null) {
            return false;
        }
        
        try {
            String sql = "SELECT COUNT(1) as count FROM tb_article_like WHERE article_id = ? AND user_id = ?";
            Map<String, Object> result = jdbcTemplate.queryForMap(sql, articleId, userId);
            return result != null && Long.parseLong(result.get("count").toString()) > 0;
        } catch (Exception e) {
            // 如果表不存在等异常情况，返回false
            log.error("查询用户点赞状态异常: articleId={}, userId={}, error={}", articleId, userId, e.getMessage());
            return false;
        }
    }
} 